<template>
  <div class="common-layout">
    <el-container id="container">
      <el-main>
        <div id="condition">
          <el-select v-model="midFilter" placeholder="请选择电影" style="width: 240px" size="large" clearable>
            <el-option v-for="movie in movies" :key="movie.mid" :label="movie.mName" :value="movie.mid"/>
          </el-select>
          <el-select v-model="cinemaFilter" placeholder="请选择影院" style="width: 240px" size="large" clearable>
            <el-option v-for="cinema in cinemas" :key="cinema.cId" :label="cinema.cName" :value="cinema.cId"/>
          </el-select>
          <el-select v-model="hallFilter" placeholder="请选择影厅" style="width: 240px" size="large" clearable>
            <el-option v-for="hall in halls" :key="hall.hId" :label="hall.hName" :value="hall.hId"/>
          </el-select>
          <el-button type="success" @click="handleQuery" size="large">查询</el-button>
          <el-button type="primary" @click="handleAdd" size="large">新增</el-button>
        </div>

        <div id="tableDiv">
          <el-table :data="tableData" border size="large" table-layout="fixed" style="text-align: center">
            <el-table-column prop="soId" label="场次ID"/>
            <el-table-column prop="movieName" label="电影名称"/>
            <el-table-column prop="cinemaName" label="影院名称"/>
            <el-table-column prop="address" label="影院地址"/>
            <el-table-column prop="hallName" label="影厅名称"/>
            <el-table-column prop="beginTime" label="开始时间"/>
            <el-table-column prop="endTime" label="结束时间"/>
            <el-table-column prop="leftSeat" label="剩余座位"/>
            <el-table-column prop="price" label="票价"/>
            <el-table-column label="操作" fixed="right" width="180">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>

      <el-footer>
        <div id="pagination">
          <el-pagination
              style="float:right"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :current-page="currentPage"
              :total="totalCount"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              background
              layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </el-footer>
    </el-container>

    <!-- 新增场次对话框 -->
    <el-dialog v-model="addDialog" title="新增场次" width="600" center>
      <el-form :model="soDto" size="large">
        <el-form-item label="电影">
          <el-select v-model="soDto.mid" placeholder="请选择电影" style="width: 240px" clearable>
            <el-option v-for="movie in movies" :key="movie.mid" :label="movie.mName" :value="movie.mid"/>
          </el-select>
        </el-form-item>
        <el-form-item label="影厅">
          <el-select v-model="soDto.hid" placeholder="请选择影厅" style="width: 240px" clearable>
            <el-option v-for="hall in halls" :key="hall.hId" :label="hall.hName" :value="hall.hId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="soDto.beginTime" type="datetime" placeholder="请选择开始时间"
                          style="width: 240px"/>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="soDto.endTime" type="datetime" placeholder="请选择结束时间"
                          style="width: 240px"/>
        </el-form-item>
        <el-form-item label="票价">
          <el-input v-model="soDto.price" placeholder="请输入票价" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="剩余座位">
          <el-input v-model="soDto.leftSeat" placeholder="请输入剩余座位数" style="width: 240px"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAddSession">新增</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑场次对话框 -->
    <el-dialog v-model="editDialog" title="编辑场次" width="600" center>
      <el-form :model="organizeNew" size="large">
        <el-form-item label="电影">
          <el-select v-model="organizeNew.mid" placeholder="请选择电影" style="width: 240px" clearable>
            <el-option v-for="movie in movies" :key="movie.mid" :label="movie.mName" :value="movie.mid"/>
          </el-select>
        </el-form-item>
        <el-form-item label="影厅">
          <el-select v-model="organizeNew.hid" placeholder="请选择影厅" style="width: 240px" clearable>
            <el-option v-for="hall in halls" :key="hall.hId" :label="hall.hName" :value="hall.hId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="organizeNew.beginTime" type="datetime" placeholder="请选择开始时间"
                          style="width: 240px"/>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="organizeNew.endTime" type="datetime" placeholder="请选择结束时间"
                          style="width: 240px"/>
        </el-form-item>
        <el-form-item label="票价">
          <el-input v-model="organizeNew.price" placeholder="请输入票价" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="剩余座位">
          <el-input v-model="organizeNew.leftSeat" placeholder="请输入剩余座位数" style="width: 240px"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialog = false">取消</el-button>
          <el-button type="primary" @click="handleEditSession">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElNotification, ElMessageBox} from 'element-plus';
import {request2} from '@/request';  // 使用封装的request2

// 表格数据、分页信息和过滤器
const midFilter = ref('');
const cinemaFilter = ref('');
const hallFilter = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const totalCount = ref(0);
const tableData = reactive([]);

// 对话框状态
const addDialog = ref(false);
const editDialog = ref(false);

// 数据模型
const soDto = reactive({
  mid: null,
  hid: null,
  beginTime: null,
  endTime: null,
  price: null,
  leftSeat: null,
});
const organizeNew = reactive({
  soId: null,
  mid: null,
  hid: null,
  beginTime: null,
  endTime: null,
  price: null,
  leftSeat: null,
});

// 下拉框数据
const cinemas = ref([]);
const halls = ref([]);
const movies = ref([]);

// 查询接口
const handleQuery = () => {
  const queryDto = {
    mid: midFilter.value,
    cid: cinemaFilter.value,
    hid: hallFilter.value,
    pageNo: currentPage.value,
    pageSize: pageSize.value,
  };

  request2({url: '/organize/selectCondition2', method: 'post', data: queryDto}).then(res => {
    if (res.code === '200' && res.data) {
      tableData.splice(0, tableData.length);
      tableData.push(...res.data.list);
      totalCount.value = res.data.totalCount;
    }
  });
};

// 新增场次
const handleAdd = () => {
  soDto.mid = null;
  soDto.hid = null;
  soDto.beginTime = null;
  soDto.endTime = null;
  soDto.price = null;
  soDto.leftSeat = null;
  addDialog.value = true;
};

// 保存新增场次
const handleAddSession = () => {
  request2({url: '/organize/addOrganize', method: 'post', data: soDto}).then(res => {
    if (res.code === '200') {
      ElNotification.success('新增成功');
      addDialog.value = false;
      handleQuery();
    }
  });
};

// 编辑场次
const handleEdit = (row) => {
  // 数据回显
  organizeNew.soId = row.soId;
  const midLoop = ref(null);
  const hidLoop = ref(null);
  movies.value.forEach((movie) => {
    if (movie.mName === row.movieName) {
      midLoop.value = movie.mid;
    }
  })
  halls.value.forEach((hall) => {
    if (hall.hName === row.hallName) {
      // TODO 这里的回显有问题，因为hName很可能重名，但是显示没问题
      hidLoop.value = hall.hId;
    }
  })
  organizeNew.mid = midLoop.value;
  organizeNew.hid = hidLoop.value;
  organizeNew.beginTime = row.beginTime;
  organizeNew.endTime = row.endTime;
  organizeNew.price = row.price;
  organizeNew.leftSeat = row.leftSeat;
  editDialog.value = true;
};

// 保存编辑场次
const handleEditSession = () => {
  request2({url: '/organize/updateOrganize', method: 'post', data: organizeNew}).then(res => {
    if (res.code === '200') {
      ElNotification.success('修改成功');
      editDialog.value = false;
      handleQuery();
    }
  });
};

// 删除场次
const handleDelete = (row) => {
  ElMessageBox.confirm('此操作将永久删除该场次，是否继续?', '提示', {type: 'warning'}).then(() => {
    request2({url: `/organize/deleteOrganize?soId=${row.soId}`, method: 'post'}).then(res => {
      if (res.code === '200') {
        ElNotification.success('删除成功');
        handleQuery();
      }
    });
  });
};

// 分页处理
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  handleQuery();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  handleQuery();
};

// 页面加载时初始化数据
onMounted(() => {
  request2({url: '/cinema/selectAll', method: 'get'}).then(res => {
    if (res.code === '200') cinemas.value = res.data;
  });

  request2({url: '/hall/selectAll', method: 'get'}).then(res => {
    if (res.code === '200') halls.value = res.data;
  });

  request2({url: '/movie/selectAll', method: 'get'}).then(res => {
    if (res.code === '200') movies.value = res.data;
  });

  handleQuery();
});
</script>
<style scoped>
.common-layout {
  width: 100%;
  height: 100%;
}

#condition {
  display: flex;
  justify-content: space-between;
}

#tableDiv {
  text-align: center;
}

#pagination {
  float: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}
</style>
